package co.yixiang.modules.system.service.impl;

import cn.hutool.core.convert.Convert;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.modules.system.domain.LoanPlan;
import co.yixiang.modules.system.domain.PartnerType;
import co.yixiang.modules.system.domain.UserIncome;
import co.yixiang.modules.system.domain.VxUser;
import co.yixiang.modules.system.dto.LoanPlanDto;
import co.yixiang.modules.system.dto.queryCriteria.LoanPlanQueryCriteria;
import co.yixiang.modules.system.mapper.LoanPlanMapper;
import co.yixiang.modules.system.service.LoanPlanService;
import co.yixiang.modules.system.service.PartnerTypeService;
import co.yixiang.modules.system.service.UserIncomeService;
import co.yixiang.modules.system.service.VxUserService;
import co.yixiang.modules.system.util.ConfigConstant;
import co.yixiang.modules.system.util.InfoFilterUtil;
import co.yixiang.modules.system.util.WxMsgPush;
import co.yixiang.modules.system.util.vo.WxMsgVo;
import co.yixiang.utils.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zf
 * @date 2021-10-10
 */
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "loanPlan")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class LoanPlanServiceImpl extends BaseServiceImpl<LoanPlanMapper, LoanPlan> implements LoanPlanService {

    @Autowired
    private final VxUserService vxUserService;

    @Autowired
    UserIncomeService userIncomeService;

    @Autowired
    PartnerTypeService partnerTypeService;

    @Autowired
    private final WxMsgPush wxMsgPush;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(LoanPlanQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<LoanPlan> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", Convert.toList(LoanPlanDto.class, page.getList()));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<LoanPlan> queryAll(LoanPlanQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(LoanPlan.class, criteria));
    }


    @Override
    public void download(List<LoanPlanDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LoanPlanDto loanPlan : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("业务员", loanPlan.getOpenId());
            map.put("业务员名称", loanPlan.getBusName());
            map.put("客户名称", loanPlan.getName());
            map.put("电话", loanPlan.getPhone());
            map.put("贷款金额", loanPlan.getMoney());
            map.put("贷款时间", loanPlan.getLoanTime());
            map.put("房产所在地", loanPlan.getHouse());
            map.put("公司所在地", loanPlan.getCompany());
            map.put("消费卷 id", loanPlan.getRid());
            map.put("贷款类型 1房贷  2 车贷  3工薪贷  4企业贷", loanPlan.getLoanType());
            map.put("业务状态 1 办理中。2 办理成功。 3 办理失败", loanPlan.getLoanStatus());
            map.put("备注", loanPlan.getRemake());
            map.put("创建时间", loanPlan.getCreateTime());
            map.put("佣金", loanPlan.getCommission());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void check(LoanPlan resources) throws Exception {
        this.updateById(resources);

        String url = ConfigConstant.TD_URL + "?id=" + resources.getId();
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String now = dtf2.format(time);

        BigDecimal oneCos = new BigDecimal(0);
        if (resources.getLoanStatus() == 3) {
            //签约
            QueryWrapper<VxUser> userWrapper = new QueryWrapper<>();
            userWrapper.eq("open_id", resources.getOpenId());
            VxUser one = vxUserService.getOne(userWrapper);

            //记录收益
            if (!StringUtils.isEmpty(resources.getCommission())) {
                //平推收益
                oneCos = resources.getCommission().multiply(ConfigConstant.PRO_POR);
                UserIncome income = UserIncome.builder()
                        .openId(one.getOpenId())
                        .partnerName(one.getAccount())
                        .name(resources.getName())
                        .money(oneCos)
                        .remake(ConfigConstant.FLAT)
                        .build();
                userIncomeService.save(income);
            }
            int i = 0;
            VxUser two = one;
            while (two.getSuperId() != 0) {
                two = vxUserService.getById(two.getSuperId());
                PartnerType partnerType = partnerTypeService.getById(two.getIdent());
                BigDecimal twoCos = resources.getCommission().multiply(partnerType.getRebate());

                UserIncome income = UserIncome.builder()
                        .openId(two.getOpenId())
                        .partnerName(two.getAccount())
                        .name(resources.getName())
                        .money(twoCos)
//                        .lowerId()
                        .remake(ConfigConstant.XIA)
                        .build();
                userIncomeService.save(income);

                String url2 = ConfigConstant.TD_URL3 + "?id=" + resources.getId();
                WxMsgVo msgVo = WxMsgVo.builder()
                        .first("您好！下级合伙人客户已经签约")
                        .keyword1(InfoFilterUtil.maskUserName(resources.getName()) + "|" + InfoFilterUtil.nameDesensitization(resources.getPhone()))
                        .keyword2(now)
                        .openId(two.getOpenId())
                        .url(url2)
                        .remark("获取收益：" + twoCos + "  元" + "点击查看详情，查看业务进展！")
                        .build();
                wxMsgPush.SendWxMsg(msgVo);
                i = i++;
                if (i == 2) {
                    break;
                }
            }
        }
        BigDecimal msg = oneCos.compareTo(new BigDecimal(0)) == 0 ? new BigDecimal(0) : oneCos;

        WxMsgVo msgVo = WxMsgVo.builder()
                .first("您好！客户专属方案审核状态已更新")
                .keyword1("客户：" + resources.getName() + "-" + resources.getPhone())
                .keyword2(now)
                .openId(resources.getOpenId())
                .url(url)
                .remark("获取收益：" + msg + "  元" + "点击查看详情，查看业务进展！")
                .build();
        wxMsgPush.SendWxMsg(msgVo);
    }

    //发送通知
//    public void sendMsg(LoanPlan resources) {
//        String url = ConfigConstant.TD_URL + "?id=" + resources.getId();
//        LocalDateTime time = LocalDateTime.now();
//
//        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//        String now = dtf2.format(time);
//        //消息推送
//        WxMsgVo msgVo = WxMsgVo.builder()
//                .first("您好！下级合伙人审核状态已更新")
//                .keyword1(resources.getName() + "｜" + resources.getPhone())
//                .keyword2(now)
//                .openId(resources.getOpenId())
//                .url(url)
//                .remark("点击查看详情，查看审核进展！")
//                .build();
//        wxMsgPush.SendWxMsg(msgVo);
//    }
}
